﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using System.ComponentModel;

namespace LinkViewer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        readonly Updater _updater;
        readonly System.Windows.Forms.Timer _updateTimer;
        bool _checkForUpdates;
        string _htmlKnownIssues = "";

        readonly BackgroundWorker _onReadyWorker;

        jcc.com.dailyez.Bad_Links[] _badLinks;
        public MainWindow()
        {
            InitializeComponent();
            //Init some globals
            _updater = new Updater();
            _updateTimer = new System.Windows.Forms.Timer {Interval = 3000};
            //initially check after 3 seconds, then change in the handler to check every hour
            _updateTimer.Tick += UpdateTimerTick;
            _updateTimer.Start();

      
           // System.Windows.Forms.Help.ShowHelp(null, "http://www.google.com/");
            lblMainTitle.Content = App.MainWindowTitle;
            var timeTimer = new System.Windows.Forms.Timer {Interval = 1000};
            timeTimer.Tick += TimeTimerTick;
            timeTimer.Start();

            //enable/disable updater
            _checkForUpdates = true;
            
            //show known issues
            var showIssuesWorker = new BackgroundWorker();
            showIssuesWorker.DoWork += ShowIssuesWorkerDoWork;
            showIssuesWorker.RunWorkerCompleted += ShowIssuesWorkerRunWorkerCompleted;
            //don't run until i make it less annoying
            //showIssuesWorker.RunWorkerAsync();

            _onReadyWorker = new BackgroundWorker();
            _onReadyWorker.DoWork += OnReadyWorkerDoWork;
            _onReadyWorker.RunWorkerCompleted +=OnReadyWorkerRunWorkerCompleted;
            _onReadyWorker.RunWorkerAsync();


           
        }

        public MainWindow(int pageToOpen)
        {
            InitializeComponent();
            //Init some globals
            _updater = new Updater();
            _updateTimer = new System.Windows.Forms.Timer {Interval = 3000};
            //initially check after 3 seconds, then change in the handler to check every hour
            _updateTimer.Tick += UpdateTimerTick;
            _updateTimer.Start();


            // System.Windows.Forms.Help.ShowHelp(null, "http://www.google.com/");
            lblMainTitle.Content = App.MainWindowTitle;
            var timeTimer = new System.Windows.Forms.Timer {Interval = 1000};
            timeTimer.Tick += TimeTimerTick;
            timeTimer.Start();

            //enable/disable updater
            _checkForUpdates = true;

            //show known issues
            var showIssuesWorker = new BackgroundWorker();
            showIssuesWorker.DoWork += ShowIssuesWorkerDoWork;
            showIssuesWorker.RunWorkerCompleted += ShowIssuesWorkerRunWorkerCompleted;
            //don't run until i make it less annoying
            //showIssuesWorker.RunWorkerAsync();

            _onReadyWorker = new BackgroundWorker();
            _onReadyWorker.DoWork += OnReadyWorkerDoWork;
            _onReadyWorker.RunWorkerCompleted += OnReadyWorkerRunWorkerCompleted;
            _onReadyWorker.RunWorkerAsync();


   

            var wrapper = new LinkWrapper();

            jcc.com.dailyez.Link[] links = jcc.StandardWebService.WebService.GetLinksFromPage(jcc.StandardWebService.GetKey(), pageToOpen);

            foreach (var link in links)
            {
                var dirLink = new DirectoryLink {Link = link};
                wrapper.Add(dirLink);
            }
            var win = new WinLinkViewer(wrapper);
            win.Show();
            
        }


        int _suspendedTotal;
        int _elevatedTotal;
        int _suspendedSinceLastRun;
        int _elevatedSinceLastRun;
        void OnReadyWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            //Log the login event
            jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, 0, 0, 0, "{Date} - {Time} {Username} logged in.");

            _badLinks = jcc.StandardWebService.WebService.GetAllBadLinks(jcc.StandardWebService.GetKey());


            
            

            var lastRun = Properties.Settings.Default.LastRun;

            foreach (var badLink in _badLinks)
            {
                if (badLink.Is_Suspended && !badLink.Is_Elevated)
                {
                    _suspendedTotal++;
                    if (badLink.Date_Reported > lastRun)
                        _suspendedSinceLastRun++;
                }

                if (!badLink.Is_Elevated) continue;

                _elevatedTotal++;
                if (badLink.Date_Reported > lastRun)
                    _elevatedSinceLastRun++;
            }

 
        }

        //made public so i could call it from the App file when emulating restart
        public void OnReadyWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            lblSuspendedCount.Content = string.Format("Total Suspended Links: {0}", _suspendedTotal);
            lblSuspendedSinceCount.Content = string.Format("New Suspeneded Links since last run: {0}", _suspendedSinceLastRun);
            lblElevatedCount.Content = string.Format("Total Elevated Links: {0}", _elevatedTotal);
            lblElevatedSinceCount.Content = string.Format("New Elevated Links since last run: {0}", _elevatedSinceLastRun);

            //see if we're suppose to open a directory immediately
            if (Properties.Settings.Default.OpenDirectory)
            {

                //see if the value is negative, if it is, that means open suspended links
                if (Properties.Settings.Default.DirectoryIDToOpen < 0)
                {
                    //if it's negative 1, that means open all suspended links (hard coded value)
                    if (Properties.Settings.Default.DirectoryIDToOpen == -1)
                    {
                        BOpenSuspendedClick(null, null);
                    }
                    else
                    {
                        //make the value positive, and open the suspended links specific folder
                        int folderID = Properties.Settings.Default.DirectoryIDToOpen * -1;

                        _worker = new BackgroundWorker();
                        _worker.DoWork += OpenSuspendedWorkerDoWork;
                        _worker.ProgressChanged += OpenSuspendedWorkerProgressChanged;
                        _worker.RunWorkerCompleted += OpenSuspendedWorkerRunWorkerCompleted;
                        _worker.WorkerReportsProgress = true;
                        progBarMain.Visibility = Visibility.Visible;

                        _worker.RunWorkerAsync(folderID);
                        App.LastFolderOpened = folderID * -1;
                    }
                }
                else
                {
                    //open standard issue directory
                    winExtractLinksProgress getLinks = new winExtractLinksProgress(Properties.Settings.Default.DirectoryIDToOpen);
                    getLinks.Show();
                }
                //set the value back to false so it doesn't open a directory on next launch
                Properties.Settings.Default.OpenDirectory = false;
                Properties.Settings.Default.Save();
            }
         
        }


        void ShowIssuesWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!Properties.Settings.Default.ShowKnownIssues) return;
            var displayKnownIssues = new DisplayBrowser(_htmlKnownIssues, "Known Issues", "http://jetnettlinkviewer.codeplex.com/wikipage?title=Known%20Issues");
            displayKnownIssues.Show();
        }

        void ShowIssuesWorkerDoWork(object s, DoWorkEventArgs e)
        {
            //show known issues just once
            if (Properties.Settings.Default.ShowKnownIssues)
            {
                _htmlKnownIssues = _updater.DownloadText("http://jetnettlinkviewer.codeplex.com/wikipage?title=Known%20Issues");

                if (!string.IsNullOrEmpty(_htmlKnownIssues))
                {
                    if (!_htmlKnownIssues.Contains("{Begin}"))
                        return;

                    _htmlKnownIssues = _htmlKnownIssues.Substring(_htmlKnownIssues.IndexOf("{Begin}") + "{Begin}".Length);

                    if (_htmlKnownIssues == null || !_htmlKnownIssues.Contains("{End}"))
                        return;

                    _htmlKnownIssues = _htmlKnownIssues.Substring(0, _htmlKnownIssues.IndexOf("{End}"));

                    
                }
                
                
            }
        }
        void UpdateTimerTick(object sender, EventArgs e)
        {
            if (_checkForUpdates)
            {
                string latestVersion = _updater.GetLatestVersionString();

                if (!string.IsNullOrEmpty(latestVersion))
                {

                    var currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                    if (currentVersion != latestVersion)
                    {
                        _checkForUpdates = false;
                        var result = MessageBox.Show(string.Format("A new version of the JetNett Link Viewer has been released, version {0}!  Would you like to go to the Link Viewer site to download the new version?", latestVersion), "New Version Released!", MessageBoxButton.YesNo, MessageBoxImage.Information);

                        if (result == MessageBoxResult.Yes)
                        {
                            string dlLink = _updater.DownloadText("http://jetnettlinkviewer.codeplex.com/wikipage?title=DownloadLink");

                            if (!string.IsNullOrEmpty(dlLink))
                            {
                                if (!dlLink.Contains("{Begin}"))
                                    return;

                                dlLink = dlLink.Substring(dlLink.IndexOf("{Begin}") + "{Begin}".Length);

                                if (dlLink == null || !dlLink.Contains("{End}"))
                                {
                                    Process.Start("http://www.codeplex.com/JetnettLinkViewer");
                                    return;
                                }

                                dlLink = dlLink.Substring(0, dlLink.IndexOf("{End}"));
                                try
                                {
                                    Process.Start(dlLink);
                                }
                                catch
                                {
                                    MessageBox.Show("Direct download failed, opening download website");
                                    Process.Start("http://www.codeplex.com/JetnettLinkViewer");
                                }

                            }
                            else
                                Process.Start("http://www.codeplex.com/JetnettLinkViewer");
                          
                        }
                        
                    }

                }
            }
            _updateTimer.Interval = 60 * 60 * 1000; //60 minutes * 60 secs in a minute * 1000 ms in a second
        }

        void TimeTimerTick(object sender, EventArgs e)
        {
            lblDate.Text = DateTime.Now.ToString("MMMM dd ");
            lblTime.Text = DateTime.Now.ToString("hh:mm:ss tt");
        }

        private void TitleBarMouseDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        private void BOpenDirectoryClick(object sender, RoutedEventArgs e)
        {
            var selFolder = new jcc.DlgSelectFolder("Select a folder to check");
            if (selFolder.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;

            var getLinks = new winExtractLinksProgress(selFolder.SelectedFolder.ID);
            getLinks.Show();
            /*
            LinkWrapper wrapper = new LinkWrapper();
            DirectoryLink link = new DirectoryLink();
            link.Link = new net.metroeguide.Link();
            link.Title = "Google";
            link.URL = "http://www.google.com";
            wrapper.Add(link);
            winLinkViewer viewer = new winLinkViewer(wrapper);
            viewer.Show();
          */
        }

        private void BCloseClick(object sender, RoutedEventArgs e)
        {
            jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, 0, 0, 0, "{Date} - {Time} {Username} logged out.");
          //  LinkViewer.Properties.Settings.Default.ShowKnownIssues = cbShowKnownIssues.IsChecked.Value;
            Properties.Settings.Default.LastRun = DateTime.Now;
            Properties.Settings.Default.Save();
            Application.Current.Shutdown(); 
        }

        private void BMinimizeClick(object sender, RoutedEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }
        BackgroundWorker _worker = null; 
        private void BOpenSuspendedClick(object sender, RoutedEventArgs e)
        {
            _worker = new BackgroundWorker();
            _worker.DoWork += OpenSuspendedWorkerDoWork;
            _worker.ProgressChanged += OpenSuspendedWorkerProgressChanged;
            _worker.RunWorkerCompleted += OpenSuspendedWorkerRunWorkerCompleted;
            _worker.WorkerReportsProgress = true;
            progBarMain.Visibility = Visibility.Visible;

            _worker.RunWorkerAsync();
            App.LastFolderOpened = -1;
            
        }
  
        private void BOpenSuspendedFolderClick(object sender, RoutedEventArgs e)
        {
            var folderSelect = new jcc.DlgSelectFolder("Select a Directory");
            if (folderSelect.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;


            _worker = new BackgroundWorker();
            _worker.DoWork += OpenSuspendedWorkerDoWork;
            _worker.ProgressChanged += OpenSuspendedWorkerProgressChanged;
            _worker.RunWorkerCompleted += OpenSuspendedWorkerRunWorkerCompleted;
            _worker.WorkerReportsProgress = true;
            progBarMain.Visibility = Visibility.Visible;
               
            _worker.RunWorkerAsync(folderSelect.SelectedFolder.ID);
            App.LastFolderOpened = folderSelect.SelectedFolder.ID * -1;
        }
        void OpenSuspendedWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progBarMain.Visibility = Visibility.Hidden;
            lblProgress.Content = "";
            var wrapper = (LinkWrapper)e.Result;
            if (wrapper.Count > 0)
            {
                var win = new WinLinkViewer(wrapper);
                win.Show();
            }

        }
        void OpenSuspendedWorkerProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progBarMain.Value = e.ProgressPercentage;
        }

        void OpenSuspendedWorkerDoWork(object s, DoWorkEventArgs e)
        {
            var folderID = 0;
            try
            {
                folderID = (int)e.Argument;
            }
            catch
            {
                folderID = 0;
            }
            lblProgress.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate() { lblProgress.Content = "Reading bad links from database"; }));
            _badLinks = jcc.StandardWebService.WebService.GetAllBadLinks(jcc.StandardWebService.GetKey());

            var totalCount = _badLinks.Length;
            var wrapper = new LinkWrapper();
            double counter = 0;
            foreach (jcc.com.dailyez.Bad_Links link in _badLinks)
            {
                var f = counter / totalCount;

                //if the link is suspended only (not elevated)
                if (link.Is_Suspended && !link.Is_Elevated)
                {
                    var dirLink = new DirectoryLink
                                      {
                                          Link =
                                              jcc.StandardWebService.WebService.GetLink(
                                                  jcc.StandardWebService.GetKey(), link.Link_ID)
                                      };

                    if (dirLink.Link == null)
                    {
                        //the link was deleted, but somehow still in the bad links database, clean it up
                        jcc.StandardWebService.WebService.DeleteBadLink(jcc.StandardWebService.GetKey(), link.ID);
                        continue;
                    }

                    
                    //if this was opened with a directory specified or not
                    if (folderID > 0)
                    {
                        jcc.com.dailyez.Page page = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), link.Original_Page_ID);
                        if (page.Folder_ID == folderID)
                            wrapper.Add(dirLink);
                    }
                    else
                        wrapper.Add(dirLink);
                }
                _worker.ReportProgress((int)(f * 100));
                counter++;
            }

            e.Result = wrapper;

        }

        private void bOpenElevated_Click(object sender, RoutedEventArgs e)
        {

            jcc.com.dailyez.Bad_Links[] links = jcc.StandardWebService.WebService.GetAllBadLinks(jcc.StandardWebService.GetKey());

            var wrapper = new LinkWrapper();
            foreach (jcc.com.dailyez.Bad_Links link in links)
            {
                if (link.Is_Elevated)
                {
                    DirectoryLink dirLink = new DirectoryLink();
                    dirLink.Link = jcc.StandardWebService.WebService.GetLink(jcc.StandardWebService.GetKey(), link.Link_ID);
                    if (dirLink.Link == null)
                    {
                        //the link was deleted, but somehow still in the bad links database, clean it up
                        jcc.StandardWebService.WebService.DeleteBadLink(jcc.StandardWebService.GetKey(), link.ID);
                        continue;
                    }
                    
                    dirLink.Elevated = link.Is_Elevated;
                    dirLink.Suspended = link.Is_Suspended;

                    wrapper.Add(dirLink);
                }
            }
            if (wrapper.Count > 0)
            {
                WinLinkViewer win = new WinLinkViewer(wrapper);
                win.Show();
            }
        }

        private void BLinkCheckerClick(object sender, RoutedEventArgs e)
        {
            jcc.StandardWebService.WebService.PurgeOldEntriesFromLinkCheckerWhitelistAsync();
            Checker checker = new Checker();
            checker.Show();
        }

        private void BViewLatestActivityClick(object sender, RoutedEventArgs e)
        {
            string[] activity = jcc.StandardWebService.WebService.GetFormattedLatestLogs(5);

            string message = "";
            foreach (string a in activity)
            {
                if (a != null)
                    message += a + "\n";
            }
            MessageBox.Show(message);
        }

        private void MenuItemClick(object sender, RoutedEventArgs e)
        {
            Process.Start("http://jetnett.com/docs/Link-Viewer.ashx");
        }

        private void MenuItemClick1(object sender, RoutedEventArgs e)
        {
            //suspend links containing certain url
            var input = new JetNettEZEditor.Dialogs.dlgInputBox("Suspend Links Containing", "Suspend Links Containing", "");
            if (input.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                jcc.com.dailyez.Link[] links = jcc.StandardWebService.WebService.GetLinksContainingURL(jcc.StandardWebService.GetKey(), input.TextEntered);
                if (links != null)
                {
                    if (MessageBox.Show(links.Length + " links found, would you like to suspend these links?", "Suspend Links", MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes)
                    {
                        Controls.LinkItem.LaunchLoader();
                        foreach (jcc.com.dailyez.Link l in links)
                            jcc.StandardWebService.WebService.SuspendLink(jcc.StandardWebService.GetKey(), l.ID);
                        Controls.LinkItem.KillLoader();
                        MessageBox.Show("Complete");
                    }
                }
                else
                    MessageBox.Show("No Links returned containing " + input.TextEntered);
            }
        }

        private void MenuItemClick2(object sender, RoutedEventArgs e)
        {
            //unsuspend links containing certain url
            JetNettEZEditor.Dialogs.dlgInputBox input = new JetNettEZEditor.Dialogs.dlgInputBox("UnSuspend Links Containing", "UnSuspend Links Containing", "");
            if (input.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
               
                jcc.com.dailyez.Bad_Links[] links = jcc.StandardWebService.WebService.GetBadLinksContainingURL(jcc.StandardWebService.GetKey(), input.TextEntered);
                if (links != null)
                {
                    if (MessageBox.Show(links.Length + " links found, would you like to unsuspend these links?", "Suspend Links", MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes)
                    {
                        Controls.LinkItem.LaunchLoader();
                        foreach (jcc.com.dailyez.Bad_Links l in links)
                            jcc.StandardWebService.WebService.UnSuspendLink(jcc.StandardWebService.GetKey(), l.Link_ID);

                       
                        Controls.LinkItem.KillLoader();
                        MessageBox.Show("Complete");
                    }
                }
                else
                    MessageBox.Show("No Links returned containing " + input.TextEntered);
            }

        }

        private void MiViewWhitelistClick(object sender, RoutedEventArgs e)
        {
            string[] whiteList = jcc.StandardWebService.WebService.GetLinkCheckerWhitelist();

            string msg = "";
            foreach (string s in whiteList)
            {
                msg += s + "\n";
            }
            MessageBox.Show(msg);
        }

        private void MiDeleteFromWhitelistClick(object sender, RoutedEventArgs e)
        {
            JetNettEZEditor.Dialogs.dlgInputBox input = new JetNettEZEditor.Dialogs.dlgInputBox("Delete From Whitelist", "Enter a URL to Delete from the whitelist", "");
            if (input.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                jcc.StandardWebService.WebService.DeleteURLFromLinkCheckerWhitelist(input.TextEntered);
            }
        }

        private void MiAddToWhiteListClick(object sender, RoutedEventArgs e)
        {
            var input = new JetNettEZEditor.Dialogs.dlgInputBox("Add to Whitelist", "Enter a URL to add to the whitelist", "");
            if (input.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                jcc.StandardWebService.WebService.AddURLToLinkCheckerWhitelist(input.TextEntered);
            }
        }

        private void BEZEditorClick(object sender, RoutedEventArgs e)
        {
            //find if the link viewer is running, if it is..set as foreground window
            var processList = Process.GetProcesses();
            foreach (var p in processList)
            {
                if (p.ProcessName != "JetNettEZEditor") continue;
                App.SetForegroundWindow(p.MainWindowHandle);
                return;
            }

            //it was not running...start it
            try
            {
                var path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Jetnett EZ Editor\\JetnettEZEditor.exe";

                if (!System.IO.File.Exists(path))
                {
                    MessageBox.Show("Cannot find EZ Editor.  Looking in: " + path);
                    return;
                }
                var info = new ProcessStartInfo
                               {FileName = path, Arguments = jcc.Login.Username + " " + jcc.Login.Password};

                Process.Start(info);
            }
            catch (Exception x)
            {
                MessageBox.Show("Error Starting the EZ Editor\n" + x);
            }
        }

        private void BLpeClick(object sender, RoutedEventArgs e)
        {
            //find if the link viewer is running, if it is..set as foreground window
            var processList = Process.GetProcesses();
            foreach (var p in processList)
            {
                if (p.ProcessName != "Link Page Editor") continue;

                App.SetForegroundWindow(p.MainWindowHandle);
                return;
            }

            //it was not running...start it
            try
            {
                Process.Start("http://dailyez.com/LPE/App.aspx");
            }
            catch
            {
                MessageBox.Show("Error Starting the Link Page Editor");
            }
        }

        private void BOpenSuspendedClick(object sender, MouseButtonEventArgs e)
        {

        }
    }
}
